package cn.ipenta.app.controller;

import cn.ipenta.core.ResultMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ipenta
 * @ClassName: dd
 * @Description: TODO
 * @date 2017-09-21 下午11:32
 */
@ControllerAdvice
public class GlobalExceptionHandler {

	private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(Exception.class)
	public @ResponseBody
	Map<String, Object> jsonErrorHandler(Exception e) throws Exception {
		logger.error("[GlobalExceptionHandler]:" + e.getMessage());
		return ResultMapper.fail(e.getMessage());
	}


	@ExceptionHandler(MethodArgumentNotValidException.class)
	public @ResponseBody Map<String, Object> handleConstraintViolationException(MethodArgumentNotValidException e) {
		List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
		List<String> errers = new ArrayList<>();
		for (FieldError fieldError : fieldErrors) {
			errers.add("字段【"+fieldError.getField()+"】:"+fieldError.getDefaultMessage());
		}

		return ResultMapper.fail(errers);
	}

}
